﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Zhongy
{
    public class PlayerModel
    {
        public string ID { private set; get; }
        public string Name { private set; get; }
        public float Score { private set; get; }
        /// <summary> 放大器设备ID （从0开始计数）</summary>
        public int deviceIndex { private set; get; }

        public PlayerModel(string id)
        {
            this.ID = id;
        }

        public PlayerModel(UserModel user)
        {
            this.ID = user.ID;
            this.Name = user.Name;

        }

        public void SetDeviceIndex(int index)
        {
            this.deviceIndex = index;
        }

        /// <summary>
        /// 与游戏原有逻辑的brianData建立连接
        /// </summary>
        public void LinkBrainData()
        {
            if (BrainData.dicIDIndex.ContainsKey(this.ID))
            {
#if DEBUG_MODEL
                Debug.Log(string.Format("建立braindata时已存在{0}玩家", this.ID));
#endif

                return;
            }

            BrainData.brain brainData = new BrainData.brain();
            BrainData.dicIDIndex.Add(this.ID, this.deviceIndex);
            brainData.deviceIndex = BrainData.dicIDIndex[this.ID];
            brainData.name = this.Name;
            BrainData.Add(brainData);


            //Loom.QueueOnMainThread(() =>
            //{
            //    //重排 StarPre
            //    BrainData.ResetBrainMapLinkRoles();
            //    BrainData.s_Instance.StarPreInit();
            //});
        }

        public void DisLinkBrainData()
        {
            if (!BrainData.dicIDIndex.ContainsKey(this.ID))
            {
#if DEBUG_MODEL
                Debug.Log(string.Format("取消braindata时不存在{0}玩家", this.ID));
#endif
                return;
            }

            int deviceIndex = BrainData.dicIDIndex[this.ID];
            BrainData.dicIDIndex.Remove(this.ID);
            BrainData.brainMap.Remove(deviceIndex);

            //Loom.QueueOnMainThread(() =>
            //{
            //    //重排 StarPre
            //    BrainData.ResetBrainMapLinkRoles();
            //    BrainData.s_Instance.StarPreInit();
            //});
        }

        /// <summary>
        /// 将脑电数据传入游戏原有逻辑braindata
        /// </summary>
        /// <param name="score"></param>
        public void TransBrainData(RevScoreData score)
        {
            if (!BrainData.dicIDIndex.ContainsKey(score.id))
            {
#if DEBUG_MODEL
                Debug.Log(string.Format("传输braindata不存在{0}玩家", this.ID));
#endif
                return;
            }

            BrainData.brain brainData = new BrainData.brain();
            brainData.deviceIndex = BrainData.dicIDIndex[score.id];
            //brainData.brainValue = (byte)(brainData.deviceIndex*10);//(byte) score.score;
            brainData.brainValue = (byte) score.score;

            brainData.bError
#if !NOVALIDITY
             = !(score.validity > 0.1f);
#else
             = false;
#endif

            BrainData.setValue(brainData);
        }
    }

    /// <summary>
    /// 玩家管理类
    /// </summary>
    public class PlayerCache
    {
        private UserCache userCache = Cache.User;

        private Dictionary<string, PlayerModel> dicID2Player 
            = new Dictionary<string, PlayerModel>();
        private List<string> indexIdLst = new List<string>();

        private static int countID = 0;
        private Dictionary<string, int> id2deviceID = new Dictionary<string, int>();

        public int GetDeviceId(string id)
        {
            if (!id2deviceID.ContainsKey(id))
                id2deviceID[id] = countID++;

            return id2deviceID[id];
        }

        public bool IsExistPlayer(PlayerModel player)
        {
            if (player == null || string.IsNullOrEmpty(player.ID))
                Debug.LogError("数据不正常");

            return IsExistPlayer(player.ID);
        }

        public bool IsExistPlayer(string id)
        {
            return dicID2Player.ContainsKey(id);
        }

        public List<string> GetPlayerIdLst()
        {
            return dicID2Player.Keys.ToList();
        }

        public void SyncPlayerState(ClientPer client, List<string> idLst)
        {
            if(idLst==null || idLst.Count<=0)
                return;

            IDictionary<string,bool> record = new Dictionary<string, bool>();
            if (dicID2Player != null && dicID2Player.Count > 0)
                record = dicID2Player.Keys.ToDictionary(item => item, item => false);

            foreach (var id in idLst)
            {
                if (IsExistPlayer(id))
                    record[id] = true;
                else
                {
                    PlayerModel player = Cache.User.IsExsitUser(id)
                        ? new PlayerModel(Cache.User.GetUser(id))
                        : new PlayerModel(id);

                    AddPlayer(client, player);
                }
            }

            foreach (var item in record)
            {
                if (item.Value == false)
                {
                    SubPlayer(item.Key);
                }
            }
        }

        public void SyncPlayerScoreData(ClientPer client, List<RevScoreData> msgLst)
        {
            if (msgLst == null || msgLst.Count <= 0)
                return;

            foreach (var msg in msgLst)
            {
                if (string.IsNullOrEmpty(msg.id))
                {
                    Debug.LogError("数据无效");
                    return;
                }

                if (!dicID2Player.ContainsKey(msg.id))
                {
                    Debug.LogError("玩家不存在，加入玩家还是抛弃数据？");
                }

                //传输braindata
                dicID2Player[msg.id].TransBrainData(msg);
            }
        }

        public void AddPlayer(ClientPer client, PlayerModel player)
        {
            if (player == null || string.IsNullOrEmpty(player.ID))
                Debug.LogError("数据不正常");

            if (IsExistPlayer(player.ID))
                Debug.LogWarning(string.Format("已存在该玩家（ID:{0}）", player.ID));
            else
            {
                player.SetDeviceIndex(GetDeviceId(player.ID));
            }

            Debug.Log(string.Format("添加了ID为{0}的玩家", player.ID));
            dicID2Player[player.ID] = player;

            player.LinkBrainData();
        }

        public void SubPlayer(PlayerModel player)
        {
            if (player == null || string.IsNullOrEmpty(player.ID))
            {
                Debug.LogError("数据不正常");
                return;
            }

            SubPlayer(player.ID);
        }

        public void SubPlayer(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                Debug.LogError("id 为空值");
            }

            if (IsExistPlayer(id))
            {
                PlayerModel player = dicID2Player[id];
                player.DisLinkBrainData();
                dicID2Player.Remove(id);

                Debug.Log(string.Format("已删除id为{0}的玩家", id));
            }
            else
            {
                Debug.Log(string.Format("不存在id为{0}的玩家", id));
            }
            
        }

        public void SubAllPlayer()
        {
            dicID2Player.Clear();
        }
    }
}
